<template>
  <!-- 容器布局：左侧30%，右侧70% -->
  <el-container class="full-height">
    <!-- 左侧区域：30% -->
    <!-- <el-aside :width="'20%'" class="left-panel">
      <ContentWrap>
        <h3>左侧内容（30%）</h3>
        <p>这里可以放置分类树、导航菜单或其他操作面板。</p>
      </ContentWrap>
    </el-aside> -->

    <!-- 右侧区域：70% -->
    <el-main class="right-panel">
      <!-- 搜索工作栏 -->
      <ContentWrap>
        <el-form class="-mb-15px" size="large" :model="queryParams" ref="queryFormRef" :inline="true"
          label-width="100px">
          <el-form-item label="维护项分类" prop="keepType">
            <el-select filterable @change="handleQuery" class="!w-240px" clearable v-model="queryParams.keepType"
              placeholder="请选择维护项分类">
              <el-option v-for="dict in keepType" :key="dict.id" :label="dict.name" :value="dict.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="维护项名称" prop="name">
            <el-input @input="handleQuery" v-model="queryParams.name" placeholder="请输入维护项名称" clearable
              @keyup.enter="handleQuery" class="!w-240px" />
          </el-form-item>
          <el-form-item>
            <el-button type="success" plain @click="handleSaveBatch">
              <Icon icon="ep:check" class="mr-5px" /> 批量提交
            </el-button>
          </el-form-item>

          <el-form-item>
            <el-switch v-model="queryParams.showCheckedOnly" class="ml-2" inline-prompt @change="handleShowTypeChange"
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" active-text="已配置"
              inactive-text="全部" />
          </el-form-item>

        </el-form>
      </ContentWrap>

      <!-- 列表 -->
      <ContentWrap>
        <el-table height="70vh" :reserve-selection="true" ref="tableRef" border :row-key="row => row.id"
          v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true"
          @selection-change="handleRowCheckboxChange">
          <el-table-column type="selection" width="55" />
          <el-table-column label="维护项分类" align="center" prop="keepTypeName" />
          <el-table-column label="维护项名称" align="center" prop="name" />
          <el-table-column label="状态" align="center" prop="status">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.MAINTENANCE_STATUS" :value="scope.row.status" />
            </template>
          </el-table-column>
          <el-table-column label="维护方法" align="center" prop="keepMethod" />
          <el-table-column label="维护标准" align="center" prop="keepNorm" />
          <el-table-column label="描述" align="center" prop="description">
            <template #default="scope">
              <div class="rich-text-content" v-html="scope.row.description"></div>
            </template>
          </el-table-column>
          <!-- <el-table-column label="创建时间" align="center" prop="createTime" :formatter="dateFormatter" width="180px" /> -->
        </el-table>
        <!-- 分页 -->
        <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
          @pagination="handlePagination" />
      </ContentWrap>

    </el-main>
  </el-container>
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { EquipmentKeepSettingApi, EquipmentKeepSetting } from '@/api/business/equipmentkeepsetting'
import { EquipmentKeepTypeApi, EquipmentKeepType } from '@/api/business/equipmentkeeptype'
import { Check } from '@element-plus/icons-vue'
import { EquipmentKeepSettingTypeApi, EquipmentKeepSettingType } from '@/api/business/equipmentkeepsettingtype'


/** 维护项设置 列表 */
defineOptions({ name: 'EquipmentKeepSetting' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

//维护类型
const keepType = ref([])
const tableRef = ref()

const loading = ref(true) // 列表的加载中
const list = ref<EquipmentKeepSetting[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  keepType: undefined,
  name: undefined,
  status: 1,
  createTime: [],
  showCheckedOnly: false,
  settingId: undefined
})
const queryFormRef = ref() // 搜索的表单

const formData = ref({
  id: undefined,
  keepSetting: [],
  name: undefined,
  cycle: undefined,
  remind: undefined,
  status: undefined,
  description: undefined
})

const checkedIds = ref<number[]>([])


// const handleRowCheckboxChange = (records: EquipmentKeepSetting[]) => {
//   checkedIds.value = records.map((item) => item.id);
//   console.log("当前选择的", checkedIds.value);

// }

const handleRowCheckboxChange = (records: EquipmentKeepSetting[]) => {
  // 当前页选中的 ID
  const currentPageIds = records.map(item => item.id)

  // 更新 allCheckedIds：当前页的选中状态覆盖旧的
  const currentPageDataIds = list.value.map(item => item.id)

  // 从 allCheckedIds 中移除当前页的所有 ID
  allCheckedIds.value = allCheckedIds.value.filter(id => !currentPageDataIds.includes(id))

  // 再把当前页选中的加进去
  allCheckedIds.value.push(...currentPageIds)

  console.log("当前所有选中项（跨页）:", allCheckedIds.value)
}


const openSetting = async (id: number) => {
  if (!id) {
    message.error("获取类型失败")
    return
  }
  queryParams.settingId = id

  try {
    const data = await EquipmentKeepSettingTypeApi.getEquipmentKeepSettingTypeDamage(id)
    formData.value = data
    const selectedIds = data.keepSetting || []
    allCheckedIds.value = data.keepSetting

    if (data.keepSetting == undefined || data.keepSetting == null) {
      formData.value.keepSetting = []
    }

    // 更新本地 checkedIds
    checkedIds.value = selectedIds

    // 等待表格数据加载完成
    await getList() // 确保 list 已经加载

    // 手动同步选中状态
    nextTick(() => {
      list.value.forEach(row => {
        if (selectedIds)
          if (selectedIds.includes(row.id)) {
            tableRef.value?.toggleRowSelection(row, true)
          }
      })
    })

    console.log("openSetting", checkedIds.value)
  } catch (err) {
    message.error("加载设置失败")
  }
}

const oldPage = ref(1) // 当前显示的页码

const allCheckedIds = ref<number[]>([]) // ✅ 必须初始化为数组

const handlePagination = async () => {
  //checkedIds.value只是当前页面选中的  应该用全部的
  if (hasUnsavedChangesOnCurrentPage()) {
    try {
      // 删除的二次确认
      await message.delConfirm("当前页面数据还未提交,确定切换到下一页?")
      await getList();
    } catch {
      queryParams.pageNo = oldPage.value
      return
    }
  } else {
    await getList();
  }
}


function hasUnsavedChangesOnCurrentPage() {
  const savedIdsOnCurrentPage = getSavedCurrentPageIds(list.value)

  // 比较两个数组是否相同（顺序无关）
  console.log("checkedIds.value.length", checkedIds.value.length);
  console.log("savedIdsOnCurrentPage.length", savedIdsOnCurrentPage.length);

  if (checkedIds.value.length !== savedIdsOnCurrentPage.length) {
    return true
  }

  const sortedCurrent = [...checkedIds.value].sort()
  const sortedSaved = [...savedIdsOnCurrentPage].sort()

  return JSON.stringify(sortedCurrent) !== JSON.stringify(sortedSaved)
}

function getSavedCurrentPageIds(currentPageData) {
  // 从 keepSetting 中筛选出在当前页数据中出现的 ID
  console.log("currentPageData", currentPageData, formData.value.keepSetting);


  return formData.value.keepSetting.filter(id =>
    currentPageData.some(item => item.id === id)
  )
}


// 控制显示类型：true=只看已配置，false=看全部
const showCheckedOnly = ref(false)

// 当滑块切换时触发
function handleShowTypeChange(value) {
  console.log('切换显示模式:', value ? '已配置的' : '全部')
  // 调用查询逻辑
  getList()
}




const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
defineExpose({ openSetting }) // 提供 open 方法，用于打开弹窗

/** 查询列表 */
const getList = async () => {
  //重新赋值 防止丢失 
  checkedIds.value = formData.value.keepSetting

  // formData.value.keepSetting = [...new Set([...formData.value.keepSetting, ...checkedIds.value])];

  // 手动同步选中状态
  console.log("页码切换", checkedIds.value, formData.value.keepSetting);

  const data = await EquipmentKeepTypeApi.getEquipmentKeepTypeListDamage();
  keepType.value = data
  loading.value = true
  try {
    const data = await EquipmentKeepSettingApi.getEquipmentKeepSettingListDamage(queryParams)

    list.value = data

    nextTick(() => {
      list.value.forEach(row => {
        if (formData.value.keepSetting && Array.isArray(formData.value.keepSetting)) {
          const rowIdStr = String(row.id);
          const found = formData.value.keepSetting.some(id => String(id) == rowIdStr);
          if (found) {
            tableRef.value?.toggleRowSelection(row, true);
          }
        }
      });
    });

  } finally {
    loading.value = false
  }
}




/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}


//     const newKeepSetting = [...new Set([
//       // ...currentKeepSetting,
//       ...checkedIds.value
//     ])];

//     formData.value.keepSetting = newKeepSetting;

//     await EquipmentKeepSettingTypeApi.updateEquipmentKeepSettingType(formData.value);
//     message.success("提交成功");
//     emit('success');
//   } catch (error) {
//     console.error("批量提交出错", error); // 建议打印 error 信息
//     ElMessage.error("提交失败，请稍后重试");
//   }

// }

const handleSaveBatch = async () => {
  try {
    formData.value.keepSetting = [...new Set(allCheckedIds.value)] // 使用全局选中项

    await EquipmentKeepSettingTypeApi.updateEquipmentKeepSettingTypeDamage(formData.value)
    message.success("提交成功")

    // ✅ 提交成功后，将当前 allCheckedIds 同步为“已保存状态”
    // 这样下次查询或刷新时，显示的就是最新状态
    // （可选）也可以清空 allCheckedIds，看业务需求

    emit('success')
  } catch (error) {
    console.error("批量提交出错", error)
    ElMessage.error("提交失败，请稍后重试")
  }
}


/** 初始化 **/
onMounted(() => {
  getList()
})
</script>

<style scoped>
/* 确保容器高度占满屏幕 */
.full-height {
  min-height: calc(100vh - 100px);
  /* 根据实际布局调整高度 */
}

.left-panel {
  padding: 16px;
  background-color: #f5f5f5;
  border-right: 1px solid #e4e4e4;
}

.right-panel {
  padding: 0;
}
</style>
